package com.yvon.im.server;

import com.yvon.im.handler.IMIdleStateHandler;
import com.yvon.im.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author : wangyufeng
 * @since : 2021-12-02
 */
@Slf4j
public class NettyServer {

    private int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>()  {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        //http解码器
                        ch.pipeline().addLast(new HttpServerCodec());
                        //支持写大数据流
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        //http聚合器
                        ch.pipeline().addLast(new HttpObjectAggregator(1024*62));
                        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
                        // 空闲检测
                        ch.pipeline().addLast(new IMIdleStateHandler());
                        ch.pipeline().addLast(new WebSocketHandler());
                    }
                });

        bind(bootstrap, port);
    }


    private static void bind(final  ServerBootstrap bootstrap, final int port) {
        bootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                log.info(new Date() + ": 端口[" + port + "]绑定成功!");
            } else {
                log.info("端口[" + port + "]绑定失败!");
            }
        });
    }


}
